package com.cc.bsp.persistence.util;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class BeansUtil {

	public static Map<String, Object> beans2MapForNullProperty(Object javaBean) {
		Map<String, Object> result = new HashMap<String, Object>();
		Method[] methods = javaBean.getClass().getDeclaredMethods();

		for (Method method : methods) {
			try {
				if (method.getName().startsWith("get")) {
					String field = method.getName();
					field = field.substring(field.indexOf("get") + 3);
					field = field.toLowerCase().charAt(0) + field.substring(1);
					Object value = method.invoke(javaBean, (Object[]) null);
					if (value instanceof String) {
						if (value != null && !"".equals(((String) value).trim())) {
							result.put(field, null == value ? null : value);
						}
					}	

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		return result;

	}
	
	public static Map<String, Object> beans2Map(Object javaBean) {
		Map<String, Object> result = new HashMap<String, Object>();
		Method[] methods = javaBean.getClass().getDeclaredMethods();

		for (Method method : methods) {
			try {
				if (method.getName().startsWith("get")) {
					String field = method.getName();
					field = field.substring(field.indexOf("get") + 3);
					field = field.toLowerCase().charAt(0) + field.substring(1);

					Object value = method.invoke(javaBean, (Object[]) null);
					result.put(field, null == value ? null : value);
				}
			} catch (Exception e) {
			}
		}

		return result;

	}
	
	public static Map<String, Object> beans2Map(Object ... javaBeans) {
		
		if (javaBeans != null && javaBeans.length == 1) {
			return beans2Map(javaBeans[0]);
		}

		Map<String, Object> result = new HashMap<String, Object>();
		
		for(Object javaBean :javaBeans){
			
			Method[] methods = javaBean.getClass().getDeclaredMethods();

			for (Method method : methods) {
				try {
					if (method.getName().startsWith("get")) {
						String field = method.getName();
						field = field.substring(field.indexOf("get") + 3);
						field = field.toLowerCase().charAt(0) + field.substring(1);
						Object value = method.invoke(javaBean, (Object[]) null);
						String simpleName  = value.getClass().getSimpleName();
						result.put(simpleName+"."+field, null == value ? null : value);
					}
				} catch (Exception e) {
				}
			}
		}
		


		return result;

	}

}
